package
{
	import as3isolib.display.IsoSprite;
	import as3isolib.display.scene.IsoScene;
	
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.utils.Dictionary;

	public class TerrainController
	{
		public static var SIZE:int = 5*Game.PPS;
		public var scene:IsoScene;
		private var m_position:Point;
		
		public var test:IsoSprite;
		
		private var m_isoSprites:Dictionary = new Dictionary(true);
		private var m_renderedSections:Vector.<Rectangle> = new Vector.<Rectangle>;
		private var m_currentSection:Rectangle;
		
		public function TerrainController(hostContainer:DisplayObjectContainer)
		{
			
			scene = new IsoScene();
			scene.hostContainer = hostContainer; 
			m_currentSection = new Rectangle(0,0,Game.TERRAIN_TILE_SIZE, Game.TERRAIN_TILE_SIZE);
			
			render();
		}
		
		public function setPosition(point:Point):void{
			point = Game.clampPoint(point, Game.TERRAIN_TILE_SIZE);

			if(!m_currentSection.containsPoint(point)){
				m_currentSection.x = point.x;
				m_currentSection.y = point.y;
				
				render();
			}
			
			
		}
		
		public function render():void{
			var sectionsToBeRendered:Vector.<Rectangle> = new Vector.<Rectangle>;
			var i:int, j:int, il:int, jl:int;
			var section:Rectangle;
			for(i = -1; i < 2; i++){
				for(j = -1; j < 2; j++){
					section = new Rectangle(m_currentSection.x + i*Game.TERRAIN_TILE_SIZE, m_currentSection.y + j*Game.TERRAIN_TILE_SIZE, Game.TERRAIN_TILE_SIZE, Game.TERRAIN_TILE_SIZE);
					sectionsToBeRendered.push(section);
				}
			}
			 
			for(i = 0, il = sectionsToBeRendered.length; i < il; i++){
				section = sectionsToBeRendered[i];
				if(!isAlreadyRendered(section)){
					
					var grassTile:Sprite = Game.getGrassTerrainTile();
					var test:IsoSprite = new IsoSprite();
					test.container.addChild(grassTile);
					test.x = section.x
					test.y = section.y
					scene.addChild(test);			
					
					scene.render(true);	
					m_isoSprites[section] = test;
					
					m_renderedSections.push(section);
				}
			}
			
			for(i = 0; i < m_renderedSections.length; i++){
				section = m_renderedSections[i];
				if(m_currentSection.topLeft.subtract(section.topLeft).length > Game.TERRAIN_TILE_SIZE*3){
					var sprite:IsoSprite = m_isoSprites[section];
					sprite.parent.removeChild(sprite);
					delete m_isoSprites[section];					
					m_renderedSections.splice(m_renderedSections.indexOf(section),1);
				}
			}
		}
		
		private function isAlreadyRendered(section:Rectangle):Boolean{
			var result:Boolean = false;
			var i:int, il:int;
			for(i = 0, il = m_renderedSections.length; i < il; i++){
				if(m_renderedSections[i].equals(section)){
					return true;
				}
			}
			
			return false;
		}
	}
}